namespace Grep.Lib.Web.UI.Extensions
{
    using System;
    using System.Collections;
    using System.Web.UI;

    public static class ControlExtensions
    {
        public static T FindChildByType<T>(this Control self)
            where T : class
        {
            var stack = new Stack(self.Controls);
            while (stack.Count > 0)
            {
                var control = stack.Pop() as Control;
                if (control is T)
                {
                    return control as T;
                }
                foreach (Control child in control.Controls)
                {
                    stack.Push(child);
                }
            }
            return null;
        }

        public static Control FindChildMatching(this Control self, Predicate<Control> matchChild)
        {
            var stack = new Stack(self.Controls);
            while (stack.Count > 0)
            {
                var control = stack.Pop() as Control;
                if (matchChild(control))
                {
                    return control;
                }
                foreach (Control child in control.Controls)
                {
                    stack.Push(child);
                }
            }
            return null;
        }
    }
}